package linkeklist;

public class Josephu {
	public static void main(String[] args) {
		int startNo = 3;
		int countNum = 4;
		int nums = 11;
		//测试
		CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
		circleSingleLinkedList.addNode(nums);
		circleSingleLinkedList.showNode();
		System.out.println("开始报数");
		circleSingleLinkedList.countNode(startNo, countNum, nums);
	}
}

//创建一个node类，表示一个节点
class Node {
	private int no;
	private Node next;

	public Node(int no) {
		this.no = no;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public Node getNext() {
		return next;
	}

	public void setNext(Node next) {
		this.next = next;
	}
}

//创建环形单向链表
class CircleSingleLinkedList {
	//创建一个first节点，先补不赋值
	private Node first = new Node(-1);

	//添加节点,构成环形链表
	public void addNode(int nums) {
		//判断nums是否合法
		if (nums < 1) {
			System.out.println("nums值有误");
			return;
		}
		Node cur = null;//辅助指针
		//使用循环创建环形链表
		for (int i = 1; i <= nums; i++) {
			//更具编号创建节点
			Node node = new Node(i);
			if (i == 1) {
				first = node;
				node.setNext(first);
				cur = first;
			}
			cur.setNext(node);
			node.setNext(first);
			cur = node;
		}
	}

	//遍历当前环形链表
	public void showNode() {
		//判断是否为空
		if (first == null) {
			System.out.println("链表为空");
			return;
		}
		Node cur = first;
		while (true) {
			System.out.printf("Node的编号 %d \n", cur.getNo());
			if (cur.getNext() == first) {
				//若成立，遍历完成
				break;
			}
			cur = cur.getNext();
		}
	}

	//根据输入，形成出圈顺序

	/**
	 * @param startNo：  表示从第几个节点开始数
	 * @param countNum： 表示数几下
	 * @param nums：     表示一共有多少节点
	 */
	public void countNode(int startNo, int countNum, int nums) {
		//判断合理性
		if (first == null || startNo < 1 || startNo > nums) {
			System.out.println("参数有误");
			return;
		}

		//创建辅助指针
		Node helper = first;
		//1.helper 指向最后一个节点
		while (true) {
			if (helper.getNext() == first) {
				//说明指向最后
				break;
			}
			helper = helper.getNext();
		}
		//2.让helper 和 first 移动 startNo-1 次，移动到改报数的节点
		for (int j = 0; j < startNo - 1; j++) {
			first = first.getNext();
			helper = helper.getNext();
		}
		//3.当小孩报数时，让first 和 helper 同时移动 countNum-1 次，然后出圈
		while (true) {
			if (helper == first) {
				break;
			}
			//移动 countNum-1 次
			for (int j = 0; j < countNum - 1; j++) {
				first = first.getNext();
				helper = helper.getNext();
			}
			//此时 first 指向的就是要弹出的节点
			System.out.printf("节点 %d 弹出 \n", first.getNo());
			//把 first 指向的节点出圈
			first = first.getNext();
			helper.setNext(first);
		}
		System.out.printf("最后留下的节点为 %d \n", first.getNo());
	}
}

